package com.ruoyi.common.utils.media;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xumh
 * @title: Base64Util
 * @projectName ruoyi
 * @description: TODO
 * @date 2024/12/1215:50
 */
public class Base64Util {
    public static final String _AES_KEY_ = "______________________chenglve____________________";

    public Base64Util() {
    }

    public static String getBase64ByInputStream(boolean bl, InputStream is, String type) {
        if (is == null) {
            return "";
        } else {
            try {
                BufferedImage bi = ImageIO.read(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(bi, type, baos);
                byte[] bytes = baos.toByteArray();
                if (bl) {
                    String ImageBinary = Base64.encodeBase64String(bytes).trim();
                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher m = p.matcher(ImageBinary);
                    return m.replaceAll("");
                } else {
                    return Base64.encodeBase64String(bytes).trim();
                }
            } catch (Exception var9) {
                var9.printStackTrace();
                return "";
            }
        }
    }

    public static String getBase64(boolean bl, byte[] ba) {
        try {
            if (ba == null) {
                return null;
            } else if (bl) {
                String ImageBinary = Base64.encodeBase64String(ba).trim();
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(ImageBinary);
                return m.replaceAll("");
            } else {
                return Base64.encodeBase64String(ba).trim();
            }
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }

    public static byte[] base64ToByteArray(String base64) {
        try {
            return base64 == null ? null : Base64.decodeBase64(base64);
        } catch (Exception var2) {
            var2.printStackTrace();
            return null;
        }
    }

    public static String getImageBinary(boolean bl, String imgPath, String type) {
        File f = new File(imgPath);

        try {
            BufferedImage bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, type, baos);
            byte[] bytes = baos.toByteArray();
            if (bl) {
                String ImageBinary = Base64.encodeBase64String(bytes).trim();
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(ImageBinary);
                return m.replaceAll("");
            } else {
                return Base64.encodeBase64String(bytes).trim();
            }
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }

    public static void saveImage(String savePath, String imageName, String imageBASE64) {
        try {
            byte[] bytes = Base64.decodeBase64(imageBASE64);
            File file = new File(savePath + File.separator + imageName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (Exception var6) {
            var6.printStackTrace();
        }

    }

    public static String getFromBase64(String s) {
        if (s != null) {
            try {
                return Base64.encodeBase64String(s.getBytes()).trim();
            } catch (Exception var2) {
                var2.printStackTrace();
            }
        }

        return null;
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(1, generateKey(encryptKey));
            return cipher.doFinal(byteContent);
        } catch (InvalidKeySpecException var4) {
            var4.printStackTrace();
        } catch (UnsupportedEncodingException var5) {
            var5.printStackTrace();
        } catch (InvalidKeyException var6) {
            var6.printStackTrace();
        } catch (NoSuchAlgorithmException var7) {
            var7.printStackTrace();
        } catch (NoSuchPaddingException var8) {
            var8.printStackTrace();
        } catch (IllegalBlockSizeException var9) {
            var9.printStackTrace();
        } catch (BadPaddingException var10) {
            var10.printStackTrace();
        }

        return null;
    }

    public static String aesEncrypt(String content, String encryptKey) {
        try {
            return Base64.encodeBase64String(aesEncryptToBytes(content, encryptKey));
        } catch (Exception var3) {
            var3.printStackTrace();
            return null;
        }
    }

    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, generateKey(decryptKey));
            byte[] result = cipher.doFinal(encryptBytes);
            return new String(result);
        } catch (InvalidKeySpecException var4) {
            var4.printStackTrace();
        } catch (InvalidKeyException var5) {
            var5.printStackTrace();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
        } catch (NoSuchPaddingException var7) {
            var7.printStackTrace();
        } catch (IllegalBlockSizeException var8) {
            var8.printStackTrace();
        } catch (BadPaddingException var9) {
            var9.printStackTrace();
        }

        return null;
    }

    public static String aesDecrypt(String encryptStr, String decryptKey) {
        try {
            return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(Base64.decodeBase64(encryptStr), decryptKey);
        } catch (Exception var3) {
            var3.printStackTrace();
            return null;
        }
    }

    private static SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(secretKey.getBytes());
        KeyGenerator kg = null;

        try {
            kg = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException var4) {
        }

        kg.init(secureRandom);
        return kg.generateKey();
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }

            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for(int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte)(high * 16 + low);
            }

            return result;
        }
    }

    public static void main(String[] args) throws Exception {
        String content = "882887819,1477476035430";
        System.out.println("加密前：" + content);
        String key = "ecms_2016_cscc";
        System.out.println("加密密钥和解密密钥：" + key);
        String encrypt = aesEncrypt(content, key);
        System.out.println("加密后：" + encrypt);
        String encode = URLEncoder.encode(encrypt, "UTF-8");
        System.out.println(encode);
        String decode = URLDecoder.decode(encode, "UTF-8");
        System.out.println(decode);
        String decrypt = aesDecrypt(decode, key);
        System.out.println("解密后：" + decrypt);
    }
}
